import tkinter as tk
from src.ui.video_display import VideoDisplay
from src.ui.button_controller import ButtonController
from src.detection.pose_classifier import PoseClassifier
from src.detection.mediapipe_wrapper import MediaPipeWrapper
from src.utils.camera_utils import CameraStream
from src.utils.report_generator import ReportGenerator
import threading
import cv2
import time
import os


class MainWindow:
    def __init__(self, root):
        self.root = root
        self.root.title("人体姿态分析系统")
        self.camera_stream = CameraStream(0)  # 0表示默认摄像头
        self.camera_stream.start()
        self.mediapipe_wrapper = MediaPipeWrapper()
        self.pose_classifier = PoseClassifier()

        self.video_display = VideoDisplay(self.root)
        self.status_label = tk.Label(self.root, text="状态：未开始")
        self.status_label.pack(side=tk.BOTTOM)

        self.is_detecting = False
        self.detection_thread = None

        self.pose_history_data = []  # 存储姿态历史数据
        self.report_generator = ReportGenerator()
        self.button_controller = ButtonController(
            self.root, self.start_detection, self.stop_detection, self.generate_report
        )

    def start_detection(self):
        self.is_detecting = True
        self.status_label.config(text="状态：检测中...")
        self.detection_thread = threading.Thread(target=self.detection_loop)
        self.detection_thread.start()

    def stop_detection(self):
        self.is_detecting = False
        self.status_label.config(text="状态：已停止")

    def detection_loop(self):
        while self.is_detecting:
            start_time = time.time()
            frame = self.camera_stream.read()
            if frame is None:
                continue

            try:
                # MediaPipe 姿态检测
                image, results = self.mediapipe_wrapper.process_frame(frame)

                # 姿态分类
                pose_label, confidence = self.pose_classifier.classify_pose(results)

                # 记录姿态数据
                self.pose_history_data.append(
                    {
                        "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
                        "pose": pose_label,
                        "confidence": confidence,
                    }
                )

                # 可视化
                if image is not None:  # 确保图像有效
                    self.video_display.update_frame(image)
                self.status_label.config(
                    text=f"状态：{pose_label} 置信度：{confidence:.2f}"
                )

            except Exception as e:
                print(f"Detection loop error: {e}")

            # 计算帧处理时间，并进行适当的休眠
            end_time = time.time()
            process_time = end_time - start_time
            sleep_time = max(0, 0.03 - process_time)  # 30 FPS
            cv2.waitKey(1)
            time.sleep(sleep_time)

    def generate_report(self):
        if not self.pose_history_data:
            tk.messagebox.showinfo("提示", "没有检测数据可供生成报告")
            return

        report_path = self.report_generator.generate(self.pose_history_data)
        tk.messagebox.showinfo("成功", f"报告已生成：{report_path}")

    def close(self):
        self.camera_stream.stop()
        self.root.destroy()
